package com.prp.gwt.server;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.prp.bo.User;
import com.prp.gwt.client.ClientConstants;

public class PortraitUploadHandler extends HttpServlet {

	private static final long serialVersionUID = -5187791428978236451L;
	private String basePath;

	@Override
	public void init(ServletConfig config) throws ServletException {
		basePath = config.getServletContext().getRealPath("/");
		super.init(config);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (null == req.getSession().getAttribute(ClientConstants.ATTR_USER)) {
			req.getRequestDispatcher("/welcome.html").forward(req, resp);
		}
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html; charset=UTF-8");
		int id = (Integer) req.getSession().getAttribute(ClientConstants.ATTR_USER);
		if (ServletFileUpload.isMultipartContent(req)) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(4096); // 缓冲区目录
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(1048576);// 最大上传大小

			List<FileItem> items = null;
			try {
				items = upload.parseRequest(req);
			} catch (FileUploadException e) {
				e.printStackTrace();
				PrintWriter writer = resp.getWriter();
				writer.write("上传失败");
				return;
			}

			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
				FileItem file = (FileItem) iter.next();
				String suffix = file.getName().substring(
						file.getName().lastIndexOf("."));
				String path = "image/portrait/" + System.currentTimeMillis()
						+ ".portrait" + suffix;
				try {
					User.deletePortrait(id, basePath);// 删除原头像
					file.write(new File(basePath + path));
					User.setPortrait(id, path);
				} catch (Exception e) {
					e.printStackTrace();
					PrintWriter writer = resp.getWriter();
					writer.write("上传失败");
					return;
				}
			}
		}
		PrintWriter writer = resp.getWriter();
		writer.write("上传成功");
	}

}
